package logic

import (
	"context"

	"paper-pro/app/paperfile/model"
	"paper-pro/app/paperfile/rpc/internal/svc"
	"paper-pro/app/paperfile/rpc/pb/paperfile"
	"paper-pro/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogic {
	return &GetLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

var ErrPaperNoExistsError = xerr.NewErrMsg("文件不存在")

func (l *GetLogic) Get(in *paperfile.GetReq) (*paperfile.PaperFileMeta, error) {
	paper, err := l.svcCtx.PaperModel.FindOne(l.ctx, in.Id)
	if err != nil && err != model.ErrNotFound {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"获取ID: %s 文件信息失败，err: %v", in.Id, err)
	}
	if paper == nil {
		return nil, errors.Wrapf(ErrPaperNoExistsError, "Get: Paper file meta ID:%s", in.Id)
	}
	if paper.UserId != in.UserId {
		return nil, errors.Wrapf(ErrPaperPermissionDenied,
			"Get: Paper file meta ID: %s failed, belong User: %d, op User: %d", in.Id, paper.UserId, in.UserId)
	}

	var paperMeta paperfile.PaperFileMeta
	err = copier.Copy(&paperMeta, paper)
	if err != nil {
		return nil, errors.Wrapf(err, "Get: Paper file meta ID: %s failed: 数据转换失败", in.Id)
	}
	paperMeta.Id = paper.ID.Hex()
	paperMeta.CreateAt = paper.CreateAt.Unix()
	paperMeta.UpdateAt = paper.UpdateAt.Unix()

	return &paperMeta, nil
}
